import 'package:flutter/cupertino.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';
import 'package:xin_nuo_pda/base/BaseController.dart';
import 'package:xin_nuo_pda/bean/lot_action_entity.dart';
import 'package:xin_nuo_pda/bean/lot_entity.dart';
import 'package:xin_nuo_pda/bean/lot_id_entity_entity.dart';
import 'package:xin_nuo_pda/http/api/lot_api.dart';
import 'package:xin_nuo_pda/routes/Routes.dart';

import '../../bean/arrtibut_balue_entity.dart';
import '../../bean/work_load_list_entity.dart';
import '../../values/constant.dart';
import 'EndWorkNextOneState.dart';

class EndWorkNextTwoController extends BaseController {
  var defectList = <WorkLoadListEntity>[];
  List<LotIdEntity> data = [];
  List<LotActionEntity> entity = [];
  var carryList = <String>[];
  late LotEntity? lotEntity;
  String listID = 'listID';
  TextEditingController controller = TextEditingController();
  double allCount = 0;

  @override
  void onInit() {
    super.onInit();
    data = Get.arguments['LOTLIST'];
    carryList = Get.arguments['DURABLEIDLIST'];
    entity = Get.arguments['LOTACTIONLIST'];
    lotEntity = Get.arguments['LOTENTITY'];
    double defectCount = Get.arguments['DEFECTCOUNT'];

    WorkLoadListEntity bean = WorkLoadListEntity();
    bean.lotId = lotEntity?.lOTID ?? '';
    bean.userName = USER;
    if(lotEntity?.TRACK_OUT_WIZARD == 'XNAssemblyTrackOutDefect'){
      allCount = lotEntity?.mAINQTY?.toDouble() ?? 0.0;
    }else {
      allCount = (lotEntity?.mAINQTY?.toDouble() ?? 0.0) - defectCount;
    }

    bean.mainQty = allCount;
    defectList.add(bean);
    update([listID]);
  }

  addWork() {
    WorkLoadListEntity entity = WorkLoadListEntity();
    entity.lotId = lotEntity?.lOTID ?? '';
    defectList.add(entity);
    update([listID]);
  }

  trackOut() async {
    double i = 0;

    defectList.forEach((element) {
      i += element.mainQty ?? 0;
    });

    if (i != allCount) {
      Get.snackbar('提示', '工作总数量与出站数量不符!');
      return;
    }

    if (controller.text.isEmpty) {
      Get.snackbar('提示', '请输入机台数量!');
      return;
    }
    List<ArrtibutBalueEntity> arrList = [];
    ArrtibutBalueEntity arr = ArrtibutBalueEntity();
    arr.aTTRIBUTENAME = 'EquipmentNumber';
    arr.aTTRIBUTEVALUE = controller.text;
    arrList.add(arr);

    Map<String, dynamic> params = {
      'ACTIONTYPE': 'DefaultTrackOut',
      'LOTLIST': data,
      'DURABLEIDLIST': carryList,
      'LOTACTIONLIST': entity,
      'WORKLOADLIST': defectList,
      'LOTATTRIBUTEVALUELIST' : arrList
    };
    var result = await LotApi.trackOut(canelToken, params: params);
    if (result.ok) {
      Fluttertoast.showToast(
        msg: "出站成功",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
        timeInSecForIosWeb: 1,
      );

      Get.offAllNamed(Routes.Tabs);
    }
  }
}
